<template>
  <div>
    <div class="detail_box">
      <el-row>
        <el-col :span="24" style="display: flex;justify-content: right;">
          <el-button size="small" @click="deleteMore()">删除</el-button>
          <el-upload
            style="margin: 0 10px;"
            class="upload-demo"
            action="" 
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUpload"
            :on-success="handleSuccess">
            <el-button type="primary" size="small">上传</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="45">
            </el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="creater" label="创建人">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat"></el-table-column>
            <el-table-column fixed="right" label="操作" width="220">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="officeOnline(scope.row.url)">预览</el-button>
                <el-button type="text" size="small" @click="downloadFile(scope.row.url)">下载</el-button>
                <el-button type="text" size="small" @click="selectedFile={...scope.row}, dialogVisible=true" style="margin: 0 20px 0 10;" >重命名</el-button>
                <el-button type="text" size="small" @click="deleteInoformation(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      title="修改名称"
      :visible.sync="dialogVisible"
      append-to-body
      width="30%">
      <el-form ref="dataForm" :rules="rules" :model="selectedFile" label-position="left" label-width="70px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="selectedFile.name" placeholder="请填写文件名称"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updName()">确 定</el-button>
      </span>
    </el-dialog>
    <el-image-viewer v-if="showImgFlag" :on-close="()=>{showImgFlag=false}" :url-list="imgList"></el-image-viewer>
  </div>
</template>
<script>
import { getProjectPage, attachment } from '@/api/project/index'
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils/index.js'
export default {
  name: "informationView",
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  props:{
    detail: {
      type: Object
    }
  },
  data() {
    return {
      showImgFlag: false,
      dialogVisible: false,
      elLoading: false,
      imgList: [],
      selected: [],
      selectedFile: {},
      tableData: [
        // {name: 'xxx资料', creater: '张三', createTime: new Date().getTime(), url: ''}
      ],
      submitData: [],
      loading: false,
      rules: {
        name: [{ required: true, message: '请填写文件名称', trigger: 'change' }],
      },
    };
  },
  created() {
    
  },
  async mounted() {
    await this.getDetail()
  },
  methods: {
    async getDetail() {
      this.openLoading()
      let params = {code: this.detail.code, pageNum: 1, pageSize: 10}
      getProjectPage(params).then(res => {
        const { data } = res
        let fileDetail = {...data.list[0]}
        this.tableData = fileDetail.attachment ? JSON.parse(fileDetail.attachment) : []
        this.closeLoading()
      }).catch(() =>{
        this.closeLoading()
      })
    },
    downloadFile(url) {
      window.location.href = url
    },
    //修改名称
    updName() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitData = [...this.tableData]
          this.submitData.forEach(item => {
            if(item.createTime === this.selectedFile.createTime) item.name = this.selectedFile.name
          })
          this.dialogVisible = false
          this.saveAttachment()
        }
      })
    },
    //删除
    deleteInoformation(row) {
      this.submitData = []
      this.tableData.forEach(item => {
        if(item.createTime != row.createTime) this.submitData.push(item)
      })
      this.saveAttachment()
    },
    deleteMore() {
      if(this.selected.length > 0) {
        this.submitData = []
        this.tableData.forEach(item => {
          let log = true
          this.selected.forEach(item1 => {
            if(item.createTime === item1.createTime) log = false
          })
          if(log) this.submitData.push(item)
        })
        this.saveAttachment()
      }
    },
    handleSelectionChange(val) {
      this.selected = val;
    },
    beforeAvatarUpload(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (fileType === 'pdf' || fileType === 'doc' || fileType === 'docx' || fileType === 'jpg' || fileType === 'png' || fileType === 'xls' || fileType === 'xlsx') {
          console.log('file');
      } else {
        this.$message.error("文件类型必须为jpg、png、doc、docx、pdf、xls、xlsx格式")
        return false
      }
    },
    officeOnline(url) {
      if(url.indexOf('.pdf') != -1) {
        window.open(url)
      } else if(url.indexOf('.doc') != -1 || url.indexOf('.docx') != -1 || url.indexOf('.xls') != -1 || url.indexOf('.xlsx') != -1){
        url = 'https://view.officeapps.live.com/op/view.aspx?src=' + url
        window.open(url)
      } else if(url.indexOf('.jpg') != -1 || url.indexOf('.png') != -1){
        this.imgList = [url];
        this.showImgFlag = true;
      } else {
        this.$message.warning('该文件格式暂不支持预览！')
      }
    },
    saveAttachment() {
      this.openLoading()
      attachment({
        id: this.detail.id,
        attachment: JSON.stringify(this.submitData)
      }).then(res=>{
        this.tableData = [...this.submitData]
        this.closeLoading()
      }).catch(err => {
        this.closeLoading()
      })
    },
    //文件上传
    handleUpload(option) {
      this.$ossUpload({
        path: option.file.name,
        file: option.file,
        folder: "ticket",
        done: res => {
          let fileUrl = res.res.requestUrls[0].split("?")[0];
          option.onSuccess(fileUrl)
        },
        fail: err => {
          console.log(err)
        }
      });
    },
    handleSuccess(res, file) {
      let obj = {name: file.name, creater: this.name, createTime: new Date().getTime(), url: file.response}
      this.submitData = [...this.tableData]
      this.submitData.push(obj)
      this.saveAttachment()
    },
    dateFormat(row, column) {
      var date = row[column.property];
      if(date) {
        return parseTime(date,'{y}-{m}-{d}')
      } else {
        return '-'
      }
    },
    openLoading(){
      this.elLoading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    closeLoading(){
      this.elLoading.close();
    },
  }
};
</script>
<style scoped="scoped" lang="scss">
.detail_box {
  padding: 20px 20px 40px 20px;
}
</style>
